//
//  SalesRankViewController.m
//  HongFuShop
//
//  Created by chirui on 2017/8/8.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "SalesRankViewController.h"
#import "SalesRandTableViewCell.h"
#import "UserPhotoListViewController.h"

@interface SalesRankViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    
    UITableView * _tableView;
    NSMutableArray * _dataArray;
    int _page;
    int _totailPage;
    NSDictionary * userDic;
}


@end

@implementation SalesRankViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    TitleView(@"活动详情")
    
    _page = 1;
    
    _dataArray = @[].mutableCopy;
    
    [self getActivityListData];
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_public_return" target:self action:@selector(back)];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_details_photo" target:self action:@selector(photoClick)];
    
    [self creatTableView];

}

-(void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)photoClick{

    if ([userDic[@"if_show"] isEqualToString:@"1"]) {
    
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.allowsEditing = YES;
        [self presentViewController:picker animated:YES completion:nil];

    
    }else {
    
        SHuiMBhudTextTimeStr(@"未参加该活动！");
    
    }
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *image = info[UIImagePickerControllerEditedImage];
    
    NSData *data =UIImageJPEGRepresentation(image, 1.0);
    
    if (image == nil) {
        
        image = info[UIImagePickerControllerOriginalImage];
        
        NSLog(@"取消了选择");
    }else {
    
        NSLog(@"上传照片");
        
        [self upIconImageRequestFor:data];
    
    }
    
//    if (_finishAction) {
//        _finishAction(image);
//    }
    
    [picker dismissViewControllerAnimated:YES completion:^{}];
}

-(void)creatTableView {
    
    _tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT- 64) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    UIView * view =[[UIView alloc]init];
    _tableView.tableFooterView = view;
    [self.view addSubview:_tableView];
    
    [_tableView registerNib:[UINib nibWithNibName:[SalesRandTableViewCell reuseIdentifier] bundle:nil] forCellReuseIdentifier:[SalesRandTableViewCell reuseIdentifier]];
    
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        _page = 1;
        [self getActivityListData];
        
        
    }];
    _tableView.mj_header = header;
    
    
    MJRefreshAutoNormalFooter *  footer =[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [self getActivityListData];
    }];
    
    footer.automaticallyRefresh = YES;
    _tableView.mj_footer =footer;
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _dataArray.count;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 90;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    if ([userDic[@"if_show"] isEqualToString:@"1"]) {
         return 90;
    }else {
    
        return 0.01;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary * dic = _dataArray[indexPath.row];
    SalesRandTableViewCell  * cell = [tableView dequeueReusableCellWithIdentifier:[SalesRandTableViewCell reuseIdentifier] forIndexPath:indexPath];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [cell.userIcon sd_setImageWithURL:ImageUrl(dic[@"avatar"]) placeholderImage:ImageName(@"img_user_default")];
    cell.nameLabel.text = [NSString stringWithFormat:@"Top:%@  %@",dic[@"rank"],dic[@"user_name"]];
    cell.numberLabel.text = [NSString stringWithFormat:@"%@票",dic[@"vote_number"]];
    cell.chooseBtn.tag =  [dic[@"entry_id"]  integerValue];
    [cell.chooseBtn addTarget:self action:@selector(chooseBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    if ([dic[@"status"] isEqualToString:@"1"]) {
        
        
    }else{
        
        cell.chooseBtn.hidden = YES;
        
        cell.typeImage.image = ImageName(@"icon_activity_unqualified");
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

     NSDictionary * dic = _dataArray[indexPath.row];
    UserPhotoListViewController * user = [[UserPhotoListViewController alloc]init];
    user.entry_id = dic[@"entry_id"];
    [self.navigationController pushViewController:user animated:YES];

}

-(void)chooseBtnClick:(UIButton *)btn{

    NSLog(@"btn.tag == %ld",btn.tag);
    [self activityVoteFor:[NSString stringWithFormat:@"%ld",btn.tag]];

}


-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    
    float height;
    
    
    if ([userDic[@"if_show"] isEqualToString:@"1"]) {
        height =  90;
        
        UIView * view =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, height)];
        view.backgroundColor = [UIColor groupTableViewBackgroundColor];
        
        UIImageView * userIcon = [[UIImageView alloc]initWithFrame:CGRectMake(10, 15, 60, 60)];
        userIcon.layer.cornerRadius = 30.f;
        userIcon.layer.masksToBounds = YES;
        [userIcon  sd_setImageWithURL:ImageUrl(userDic[@"avatar"]) placeholderImage:ImageName(@"img_user_default")];
        [view addSubview:userIcon];
        
        //    UIImageView * pointImage = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH-40, 0, 40, 40)];
        //    pointImage.image = ImageName(@"icon_activity_unqualified");
        //    [view addSubview:pointImage];
        
        UILabel * pointlabel =[[UILabel alloc]initWithFrame:CGRectMake(80, 52, WIDTH - 130, 20)];
        pointlabel.font = [UIFont systemFontOfSize:14];
        pointlabel.text =[NSString stringWithFormat:@"%@票",userDic[@"vote_number"]];
        pointlabel.textColor = [UIColor redColor];
        [view addSubview:pointlabel];
        
        UILabel * label =[[UILabel alloc]initWithFrame:CGRectMake(80, 15, WIDTH - 90, 20)];
        label.font = [UIFont systemFontOfSize:15];
        label.text =[NSString stringWithFormat:@"Top:%@  %@",userDic[@"rank"],@"本人"];
        [view addSubview:label];
        
        return view;

    }else {
        height = 0.01;
        
        return nil;
    }
   
}

-(void)getActivityListData{
    
    
    if (_totailPage != 0) {
        if(_page == _totailPage + 1){
            [_tableView.mj_footer setState: MJRefreshStateNoMoreData];
            
            return ;
        }
    }
    NSDictionary * dic = @{@"activity_id":self.activity_id,
                           @"page":[NSString stringWithFormat:@"%d",_page],
                           @"perpage":@"10",
                           @"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token")
                           };
    
    //    SHuiMBhubNoTimeStr(@"正在加载...");
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_activityTopList_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            _totailPage =  [responseObject[@"datas"][@"total_page"] intValue];
            
            userDic = responseObject[@"datas"][@"user_info"];
            if (_page==1) {
                
                if (_dataArray) {
                    
                    [_dataArray removeAllObjects];
                }
                if ([responseObject[@"datas"][@"list"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"datas"][@"list"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }else {
                
                if ([responseObject[@"datas"][@"list"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"datas"][@"list"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                
                if (_dataArray.count>0) {
                    //                    noBodyView.hidden =YES;
                    if (_dataArray.count<10) {
                        
                        _tableView.mj_footer.hidden = YES;
                    }else {
                        _tableView.mj_footer.hidden = NO;
                    }
                }else {
                    _tableView.mj_footer.hidden = YES;
                    //                    noBodyView.hidden =NO;
                    //
                    //                    [self.view addSubview:noBodyView];
                }
                [_tableView.mj_header endRefreshing];
                [_tableView.mj_footer endRefreshing];
                [_tableView reloadData];
                
            });
            
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"网络错误请重试！");
    }];
    
}

-(void)activityVoteFor:(NSString *)entry{

    
    NSDictionary * dic = @{@"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"entry_id":entry};
    SHuiMBhubNoTimeLoding;
    [PostNetWorking postNetWorkingStr:RequestUrlStr(activity_vote_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
           
            SHuiMBhudTextTimeStr(@"投票成功");
            
            _page = 1;
            [self getActivityListData];
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
    }];

}



// 只有头像的
-(void)upIconImageRequestFor:(NSData*)data {
    
    
    NSDictionary * dic = @{@"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"entry_id":userDic[@"entry_id"],
                           @"activity_id":self.activity_id,
                          };
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    SHuiMBhubNoTimeStr(@"正在提交...");
    [manager POST:RequestUrlStr(uploadImage_act_api) parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        [formData appendPartWithFileData:data name:@"image" fileName:fileName mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        //打印下上传进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]==200) {
            
            
            SHuiMBhudTextTimeStr(@"提交成功");
            
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                
//                [self.navigationController popViewControllerAnimated:YES];
//            });
//            
        }else{
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){
        
        SHuiMBHidleYes;
        
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
        
    } ];
    
}



@end
